// pages/socket/socket.js
const app = getApp();
Page({
  data: {
    socketOpen: false,
    receivedMessage: ''
  },
  onLoad: function (options) {
    var that = this;
    wx.connectSocket({
      url: 'ws://' + app.globalData.host + '/websocket/1'
    })
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')
      that.setData({
        socketOpen: true
      })
    })
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
  },

  send:function (e) {
    var message = e.detail.value.message;
    if (this.data.socketOpen) {
      wx.sendSocketMessage({
        data: message
      });
    }
  },
  onShow: function () {
    var that = this;
    wx.onSocketMessage(function (res) {
      that.setData({
        receivedMessage: res.data
      });
      wx.showModal({
        title: '提示',
        content: '有新的订单啦，点击确定刷新',
        success: function(res) {
          if(res.confirm) {
            console.log('刷新')
          } else {
            console.log('不刷新')
          }
        }
      })
    })
  }
  
})